import { InfiniteScroll, List } from "antd-mobile";
import { useEffect, useState } from "react";
import { getListApi, type ListItem } from "@/api";
import Article from "@/components/Article";

const HomeList = ({ channel_id }) => {
  const [hasMore, setHasMore] = useState(true)

  const [list, setList] = useState<ListItem[]>([]);
  const [timestamp, setTimestamp] = useState(`${new Date().getTime()}`)
  const getList = async () => {
    try {
      const res = await getListApi({
        channel_id,
        timestamp: timestamp,
      });

      setList([...list, ...res.data.data.results])
      setTimestamp(res.data.data.pre_timestamp)
      if (res.data.data.results.length === 0) {
        setHasMore(false)
      }
    } catch (error) {
      console.log("error", error);
    }
  };

  useEffect(() => {
    getList();
  }, [channel_id]);

  const loadMore = async () => {
    await getList();
  }

  return (
    <>
      <List>
        {
          list.map((item) => (
              <Article key={item.art_id} item={item}></Article>
            )
          )
        }
      </List>
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={18}></InfiniteScroll>
    </>
  );
};

export default HomeList;
